using System;
using System.Activities;
using Microsoft.Xrm.Sdk.Workflow;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Crm.Sdk.Messages;

namespace CRM2011WorkflowUtilities
{
    internal static class Helpers
    {
        public static void Throw(string message, Exception innerException = null)
        {
            if (innerException == null)
            {
                throw new InvalidPluginExecutionException(message);
            }
            else
            {
                throw new InvalidPluginExecutionException(message, innerException);
            }
        }

        public static QueryExpression ConvertRollupQueryToQueryExpression(EntityReference rollupQueryEr, IOrganizationService service)
        {
            Entity rollupQuery = service.Retrieve(rollupQueryEr.LogicalName, rollupQueryEr.Id, new ColumnSet("fetchxml"));
            FetchXmlToQueryExpressionRequest req = new FetchXmlToQueryExpressionRequest()
            {
                FetchXml = rollupQuery["fetchxml"] as string,
            };

            FetchXmlToQueryExpressionResponse resp = (FetchXmlToQueryExpressionResponse)service.Execute(req);
            return resp.Query;
        }
    }
}
